#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
启动所有服务的便捷脚本

使用方法:
    python start_all.py [--signaling-host HOST] [--signaling-port PORT] [--web-port PORT]

示例:
    python start_all.py --signaling-host 0.0.0.0 --signaling-port 5555 --web-port 5000
"""

import sys
import os
import argparse
import subprocess
import time
import signal
import threading
from typing import List

class ServiceManager:
    """服务管理器"""
    
    def __init__(self):
        self.processes: List[subprocess.Popen] = []
        self.running = True
    
    def start_service(self, name: str, cmd: List[str], cwd: str = None) -> subprocess.Popen:
        """启动服务"""
        print(f"启动 {name}...")
        print(f"命令: {' '.join(cmd)}")
        
        try:
            process = subprocess.Popen(
                cmd,
                cwd=cwd or os.getcwd(),
                stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT,
                universal_newlines=True,
                bufsize=1
            )
            
            self.processes.append(process)
            
            # 启动输出监控线程
            output_thread = threading.Thread(
                target=self._monitor_output,
                args=(process, name),
                daemon=True
            )
            output_thread.start()
            
            print(f"{name} 已启动 (PID: {process.pid})")
            return process
            
        except Exception as e:
            print(f"启动 {name} 失败: {e}")
            return None
    
    def _monitor_output(self, process: subprocess.Popen, name: str):
        """监控进程输出"""
        try:
            for line in iter(process.stdout.readline, ''):
                if line and self.running:
                    print(f"[{name}] {line.rstrip()}")
        except Exception as e:
            if self.running:
                print(f"[{name}] 输出监控错误: {e}")
    
    def stop_all(self):
        """停止所有服务"""
        self.running = False
        print("\n正在停止所有服务...")
        
        for i, process in enumerate(self.processes):
            if process and process.poll() is None:
                print(f"停止进程 {process.pid}...")
                try:
                    process.terminate()
                    # 等待进程优雅退出
                    try:
                        process.wait(timeout=5)
                    except subprocess.TimeoutExpired:
                        print(f"强制终止进程 {process.pid}")
                        process.kill()
                        process.wait()
                except Exception as e:
                    print(f"停止进程失败: {e}")
        
        print("所有服务已停止")
    
    def wait_for_services(self):
        """等待服务运行"""
        try:
            while self.running and any(p.poll() is None for p in self.processes if p):
                time.sleep(1)
        except KeyboardInterrupt:
            print("\n收到中断信号...")
        finally:
            self.stop_all()

def main():
    parser = argparse.ArgumentParser(description='启动WebRTC P2P Demo所有服务')
    parser.add_argument('--signaling-host', default='0.0.0.0', help='信令服务器地址 (默认: 0.0.0.0)')
    parser.add_argument('--signaling-port', type=int, default=5555, help='信令服务器ZMQ端口 (默认: 5555)')
    parser.add_argument('--web-port', type=int, default=5000, help='Web服务端口 (默认: 5000)')
    parser.add_argument('--remote-only', action='store_true', help='只启动远程服务器')
    parser.add_argument('--signaling-only', action='store_true', help='只启动信令服务器')
    
    args = parser.parse_args()
    
    print("="*60)
    print("WebRTC P2P Demo - 服务启动器")
    print("="*60)
    print(f"信令服务器: {args.signaling_host}:{args.signaling_port}")
    print(f"Web服务: http://{args.signaling_host}:{args.web_port}")
    print("="*60)
    
    manager = ServiceManager()
    
    # 设置信号处理
    def signal_handler(signum, frame):
        manager.stop_all()
        sys.exit(0)
    
    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)
    
    try:
        script_dir = os.path.dirname(os.path.abspath(__file__))
        
        if not args.remote_only:
            # 启动信令服务器
            signaling_cmd = [
                sys.executable, 'start_signaling_server.py',
                '--host', args.signaling_host,
                '--port', str(args.web_port),
                '--zmq-port', str(args.signaling_port)
            ]
            
            signaling_process = manager.start_service(
                "信令服务器", 
                signaling_cmd, 
                script_dir
            )
            
            if not signaling_process:
                print("信令服务器启动失败")
                return
            
            # 等待信令服务器启动
            print("等待信令服务器启动...")
            time.sleep(3)
        
        if not args.signaling_only:
            # 启动远程服务器
            remote_cmd = [
                sys.executable, 'start_remote_server.py',
                '--signaling-host', args.signaling_host,
                '--signaling-port', str(args.signaling_port)
            ]
            
            remote_process = manager.start_service(
                "远程服务器", 
                remote_cmd, 
                script_dir
            )
            
            if not remote_process:
                print("远程服务器启动失败")
                return
        
        print("\n" + "="*60)
        print("所有服务已启动！")
        print("="*60)
        print("")
        print("使用说明:")
        print(f"1. 在浏览器中访问: http://localhost:{args.web_port}")
        print("2. 点击'连接信令服务器'")
        print("3. 点击'开始通话'建立WebRTC连接")
        print("4. 在消息框中输入消息并发送")
        print("5. 观看远程视频流")
        print("")
        print("按 Ctrl+C 停止所有服务")
        print("="*60)
        
        # 等待服务运行
        manager.wait_for_services()
        
    except Exception as e:
        print(f"启动失败: {e}")
        manager.stop_all()
        sys.exit(1)

if __name__ == '__main__':
    main()